import axios from 'axios'
import md5 from 'md5'
import  {ElMessage} from 'element-plus'

const curl = ({
    url,
    method = 'post',
    query = {},
    headers = {},
    data = {},
    responseType = 'json',
    timeout = 60000,
}) => {
    const signKey = 'eycdlfdsnaswal24nn234m321'
    const st = Date.now()
    const daoHeaders = {
        ...headers,
        's_sign': md5(`${signKey}_${st}`),
        's_t': st,
    }
    if (url.indexOf('/api/proj') > -1 && window.projKey) {
        daoHeaders.proj_key = window.projKey
    }
    const axiosConfig = {
        url,
        method,
        params: query,
        data,
        responseType,
        timeout,
        headers: {
            ...daoHeaders,
        }
    }

    return axios(axiosConfig).then((res) => {
        const resData = res.data || {}

        const { success, code, msg } = resData
        if (!success) {
            if (code == 442) {
                ElMessage.error('请求参数异常')
            } else if (code == 445) {
                ElMessage.error('请求签名不合法')
            } else if (code == 50000) {
                ElMessage.error(msg || '服务器异常')
            } else if (code == 446) {
                ElMessage.error(msg || '缺少必要参数')
            } else {
                ElMessage.error(msg)
            }

            console.error(msg)
            return Promise.resolve({ success, code, msg })
        }
        const { data, metaData } = resData
        return Promise.resolve({ success, data, metaData })
    }).catch((err) => {
        const { message } = err
        if (message.match(/timeout/)) {
            return Promise.resolve({
                code: 504,
                msg: '请求超时',
            })
        }

        return Promise.resolve(err)
    })
}

export default curl